﻿// owner 蒋家伟

#include "DocumentManager.h"

// jsdk
#include "Document.h"
#include "Dbg_Warn_Define.h"
#include "IDocumentChangedEvent.h"
#include "DocumentChangedEventArgs.h"

using namespace jsdk;

namespace
{
    static IDocument::RunTimeId s_RunTimeId = 0;
}

jsdk::DocumentManager& jsdk::DocumentManager::get()
{
    static DocumentManager s_DocumentManager;
    return s_DocumentManager;
}

jsdk::IDocument* jsdk::DocumentManager::createEmptyDocument()
{
    OwnerPtr<Document> opDocment = Document::createEmpty();
    DBG_WARN_AND_RETURN_FALSE_UNLESS(opDocment, L"文档创建失败", L"蒋家伟", L"2023-12-19");
    opDocment->setRunTimeId(++s_RunTimeId);
    IDocument::RunTimeId runtimeId = opDocment->getRunTimeId();
    IDocument* pDoc = opDocment.get();
    if (m_RunTimeIdToDocUMap.insert(std::make_pair(runtimeId, transformOwnerShip(opDocment))).second)
    {
        IDocumentChangedEvent* pDocumentChangedEvent = IDocumentChangedEvent::get();
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDocumentChangedEvent, L"文档事件未初始化", L"蒋家伟", L"2023-12-19");
        DocumentChangedEventArgs args(pDoc, jsdk::DocumentChangedType::AfterOpenDocument);
        pDocumentChangedEvent->sendEvent(&args);
        return pDoc;
    }
    return nullptr;
}

IDocument* jsdk::DocumentManager::openDocument(const std::wstring& path)
{
    OwnerPtr<Document> opDocment = Document::create(path);
    DBG_WARN_AND_RETURN_FALSE_UNLESS(opDocment, path + L"文档加载失败", L"蒋家伟", L"2023-12-19");
    opDocment->setRunTimeId(++s_RunTimeId);
    IDocument::RunTimeId runtimeId = opDocment->getRunTimeId();
    IDocument* pDoc = opDocment.get();
    if (m_RunTimeIdToDocUMap.insert(std::make_pair(runtimeId, transformOwnerShip(opDocment))).second)
    {
        IDocumentChangedEvent* pDocumentChangedEvent = IDocumentChangedEvent::get();
        DBG_WARN_AND_RETURN_NULLPTR_UNLESS(pDocumentChangedEvent, L"文档事件未初始化", L"蒋家伟", L"2023-12-19");
        DocumentChangedEventArgs args(pDoc, jsdk::DocumentChangedType::AfterOpenDocument);
        return pDoc;
    }
    return nullptr;
}
